﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SmartDeviceProject9
{
    public partial class SaleOutStock : Form
    {
        public SaleOutStock()
        {
            InitializeComponent();
        }
        public Form ParentForm { get; set; }

        private bool closeNoEnsure = true;
        private void ProductionStock_Closing(object sender, CancelEventArgs e)
        {

            if (closeNoEnsure)
            {
                if (MessageBox.Show("关闭后，当前数据将丢失，是否继续？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    closeNoEnsure = false;
                    this.Close();

                }
            }
            else
            {

                e.Cancel = false;
            }
            ParentForm.Show();
        }
        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void cbxCheckWH_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void label3_ParentChanged(object sender, EventArgs e)
        {

        }

        private void tbxCheckNum_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 销售订单取值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxCheckNum_KeyUp(object sender, KeyEventArgs e)
        {
            #region 销售订单回车

            if (e.KeyCode == Keys.Enter)
            {
                string orgId = this.cbxCheckOrg.SelectedValue as string;
                string billNo = this.tbxCheckNum.Text.Trim();
                if (string.IsNullOrEmpty(billNo) || billNo == "" || string.IsNullOrEmpty(orgId) || orgId == "")
                    return;
                DataSet dataS = Context.Service.GetSaleOrder(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, billNo, orgId);
                if (dataS != null)
                {
                    foreach (DataRow row in dataS.Tables[1].Rows)
                    {
                        if (Convert.ToDecimal(row["FStockBaseCanOutQty"]) <= 0)
                        {
                            MessageBox.Show("该订单可出数量小于或等于0");
                            dataS = null;
                        }
                    }
                }
                
                if (dataS != null)
                {
                    //清空数据
                    this.tbxCheckNum.Text = string.Empty;
                    this.tbxPreBillNo.Text = string.Empty;
                    DataGrid2Table.Clear();
                    bindDataSource.Clear();
                    FPkValue = string.Empty;
                    //设置当前销售编号
                    tbxPreBillNo.Text = billNo;
                    //设置组织
                    DataTable orgTable = (DataTable)this.cbxCheckOrg.DataSource;

                    //主存主键
                    FPkValue = Convert.ToString(dataS.Tables[0].Rows[0]["Id"]);
                    //设置组织
                    int i = -1;
                    foreach (DataRow row in orgTable.Rows)
                    {
                        i++;
                        if (Convert.ToString(row["OrgId"]) == Convert.ToString(dataS.Tables[0].Rows[0]["FSaleOrgId"]))
                        {
                            break;
                        }
                    }
                    if (i >= 0)
                    {
                        this.cbxCheckOrg.SelectedIndex = i;
                        
                        
                        Type type = typeof(string);

                        //销售订单单据体明细
                        foreach (DataRow row in dataS.Tables[1].Rows)
                        {
                            DataRow dr = DataGrid2Table.NewRow();
                            //明细Id
                            dr["ID"] = row["Id"];
                            
                            dr["原纸名称"] = row["FMaterialName"];
                            dr["FMaterialNum"] = row["FMaterialNum"];

                            dr["幅宽"] = row["FAuxPropId"];
                            dr["FAuxPropId"] = row["FAuxPropId"];

                            dr["可出数量"] = row["FStockBaseCanOutQty"];

                            dr["单位"] = row["FBaseUnitId"];

                            dr["领料量"] = 0;

                            //销售数量
                            dr["Qty"] = row["FQty"];

                            DataGrid2Table.Rows.Add(dr);
                        }
 
                    }

                }
                else
                {
                    MessageBox.Show("未查到 销售订单编号 信息");
                }
            }


            #endregion
        }

        /// <summary>
        /// 条码回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string s = this.tbxCode.Text.Trim();        //条码
                this.tbxCode.Text = string.Empty;
                this.tbxCode.Focus();
                if (string.IsNullOrEmpty(s) || s == "")
                    return;

                string checkNum = this.tbxPreBillNo.Text.Trim();    //当前生产备料单编号
                if (string.IsNullOrEmpty(checkNum) || checkNum == "")
                {
                    MessageBox.Show("请先录入销售定单编号");
                    this.tbxCode.Text = string.Empty;
                    return;
                }
                

                string orgId = this.cbxCheckOrg.SelectedValue as string;
                string stockId = this.cbxOutStock.SelectedValue as string;
                if (orgId == null || orgId == "")
                {
                    MessageBox.Show("查找失败：当前用户无组织");
                    return;
                }
                if (stockId == null || stockId == "")
                {
                    MessageBox.Show("查找失败：未找到仓库");
                    return;
                }
                foreach (DataRow dr in DataGrid2Table.Rows)
                {
                    
                }
                //  物料编码           物料名        条码      基础数量     基础单位       幅宽        芯径            密度
                //FMaterialId,  FMaterialId.Name, FBarCode,  FBaseQty,  FBaseUnitId,    FAuxPropId  ,FDiameter   ,   FDensity   
                DataSet dataSet = Context.Service.GetCodeDetail(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, s, orgId, stockId,true);
                if (dataSet != null)
                {

                    bool isbool = true;
                    DataTable table = dataSet.Tables[0];
                    string rowMater;
                    decimal LL;
                    decimal qty;
                    foreach (DataRow dr in table.Rows)
                    {
                        string Mat = Convert.ToString(dr["FMaterialId"]);        //物料编码
                        string FK = Convert.ToString(dr["FAuxPropId"]);             //幅宽

                        //销售订单明细
                        foreach (DataRow row in DataGrid2Table.Rows)
                        {
                            //物料
                            rowMater = Convert.ToString(row["FMaterialNum"]);
                            //领料量
                            LL = Convert.ToDecimal(row["领料量"]);
                            //&& Convert.ToDecimal(row["可出数量"]) >= (LL + Convert.ToDecimal(dr["FBaseQty"]))
                            if (Mat == rowMater && FK == Convert.ToString(row["FAuxPropId"]) )
                            {

                                isbool = false;

                                qty = 0;
                                foreach (DataRow bds in bindDataSource.Rows)
                                {
                                    if (Mat == Convert.ToString(bds["FMaterialId"]) && FK == Convert.ToString(bds["FAuxPropId"]))
                                        qty++;
                                }
                                if (qty >= Convert.ToDecimal(row["Qty"]))
                                {
                                    MessageBox.Show("加载失败：条码个数不可大于销售数量");
                                    return;
                                }


                                row["领料量"] = (LL + Convert.ToDecimal(dr["FBaseQty"])).ToString("G");
                                //添加条码列表
                                DataRow nrow = bindDataSource.NewRow();

                                nrow["Id"] = row["Id"];

                                nrow["条码"] = dr["FBarCode"];
                                nrow["FBarCode"] = dr["FBarCode"];

                                nrow["原纸名称"] = dr["FMaterialFName"];
                                nrow["FMaterialId"] = Mat;

                                nrow["幅宽"] = FK;
                                nrow["FAuxPropId"] = FK;

                                nrow["数量"] = Convert.ToDecimal(dr["FBaseQty"]).ToString("0.##");
                                nrow["Qty"] = dr["FBaseQty"];

                                nrow["单位"] = dr["FBaseUnitId"];
                                nrow["UnitId"] = dr["FBaseUnitId"];

                                bindDataSource.Rows.Add(nrow);

                                
                            }
                        }
                        if (isbool)
                        {
                            MessageBox.Show("未找到符合条码的明细信息,或者将会超领");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("未查到条码信息");
                }
            }
        }
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Return_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        DataTable bindDataSource;
        DataTable DataGrid2Table;
        //源单主键
        string FPkValue = string.Empty;
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaleOutStock_Load(object sender, EventArgs e)
        {
            Type type = typeof(string);

            //条码
            bindDataSource = new DataTable();
            bindDataSource.TableName = "条码列表";
            //源单单据体主键Id
            bindDataSource.Columns.Add(new DataColumn("ID", type));
            //条码
            bindDataSource.Columns.Add(new DataColumn("FBarCode", type));
            bindDataSource.Columns.Add(new DataColumn("条码", type));
            //物料编码
            bindDataSource.Columns.Add(new DataColumn("FMaterialId", type));
            bindDataSource.Columns.Add(new DataColumn("原纸名称", type));
            //幅宽编码
            bindDataSource.Columns.Add(new DataColumn("FAuxPropId", type));
            bindDataSource.Columns.Add(new DataColumn("幅宽", type));
            //数量
            bindDataSource.Columns.Add(new DataColumn("Qty", type));
            bindDataSource.Columns.Add(new DataColumn("数量", type));
            //单位
            bindDataSource.Columns.Add(new DataColumn("UnitId", type));
            bindDataSource.Columns.Add(new DataColumn("单位", type));

            this.BillSubBody.DataSource = bindDataSource;


            #region 条码单据体视图设置

            DataGridTableStyle billView = new DataGridTableStyle();

            DataGridTextBoxColumn tc3 = new DataGridTextBoxColumn();
            tc3.Width = 60;
            tc3.HeaderText = "条码";
            tc3.MappingName = "条码";
            DataGridTextBoxColumn tc4 = new DataGridTextBoxColumn();
            tc4.Width = 70;
            tc4.HeaderText = "原纸名称";
            tc4.MappingName = "原纸名称";
            DataGridTextBoxColumn tc5 = new DataGridTextBoxColumn();
            tc5.Width = 40;
            tc5.HeaderText = "幅宽";
            tc5.MappingName = "幅宽";
            DataGridTextBoxColumn tc6 = new DataGridTextBoxColumn();
            tc6.Width = 45;
            tc6.HeaderText = "数量";
            tc6.MappingName = "数量";
            DataGridTextBoxColumn tc7 = new DataGridTextBoxColumn();
            tc7.Width = 30;
            tc7.HeaderText = "单位";
            tc7.MappingName = "单位";



            billView.GridColumnStyles.Add(tc3);
            billView.GridColumnStyles.Add(tc4);
            billView.GridColumnStyles.Add(tc5);
            billView.GridColumnStyles.Add(tc7);
            billView.GridColumnStyles.Add(tc6);





            billView.MappingName = "条码列表";

            this.BillSubBody.TableStyles.Add(billView);
            #endregion



            //销售订单明细

            DataGrid2Table = new DataTable();
            DataGrid2Table.TableName = "销售订单列表";
            //明细Id
            DataGrid2Table.Columns.Add(new DataColumn("ID", type));
            DataGrid2Table.Columns.Add(new DataColumn("原纸名称", type));
            DataGrid2Table.Columns.Add(new DataColumn("FMaterialNum", type));
            DataGrid2Table.Columns.Add(new DataColumn("幅宽", type));
            DataGrid2Table.Columns.Add(new DataColumn("FAuxPropId", type));
            DataGrid2Table.Columns.Add(new DataColumn("可出数量", type));
            DataGrid2Table.Columns.Add(new DataColumn("FOutQty", type));
            DataGrid2Table.Columns.Add(new DataColumn("单位", type));
            DataGrid2Table.Columns.Add(new DataColumn("领料量", type));
            DataGrid2Table.Columns.Add(new DataColumn("FReceiveQty", type));

            //销售数量
            DataGrid2Table.Columns.Add(new DataColumn("Qty", type));


            this.BillBody.DataSource = DataGrid2Table;


            #region 生产备料明细视图设置

            DataGridTableStyle t = new DataGridTableStyle();

            DataGridTextBoxColumn c2 = new DataGridTextBoxColumn();
            c2.Width = 70;
            c2.HeaderText = "原纸名称";
            c2.MappingName = "原纸名称";
            DataGridTextBoxColumn c3 = new DataGridTextBoxColumn();
            c3.Width = 40;
            c3.HeaderText = "幅宽";
            c3.MappingName = "幅宽";
            DataGridTextBoxColumn c4 = new DataGridTextBoxColumn();
            c4.Width = 45;
            c4.HeaderText = "可出数量";
            c4.MappingName = "可出数量";
            DataGridTextBoxColumn c5 = new DataGridTextBoxColumn();
            c5.Width = 45;
            c5.HeaderText = "领料量";
            c5.MappingName = "领料量";
            DataGridTextBoxColumn c6 = new DataGridTextBoxColumn();
            c6.Width = 30;
            c6.HeaderText = "单位";
            c6.MappingName = "单位";


            t.GridColumnStyles.Add(c2);
            t.GridColumnStyles.Add(c3);

            t.GridColumnStyles.Add(c4);
            t.GridColumnStyles.Add(c5);
            t.GridColumnStyles.Add(c6);




            t.MappingName = "销售订单列表";
            this.BillBody.TableStyles.Add(t);

            #endregion


            //设置组织
            DataTable table = new DataTable();
            table.Columns.Add("OrgId", type);
            table.Columns.Add("Name", type);
            int i = -1;
            int selectIndex = -1;
            foreach (var org in Context.Orgs)
            {
                i++;
                DataRow row = table.NewRow();
                row["OrgId"] = org.Value.OrgId;
                row["Name"] = org.Value.Name;
                
                if (org.Value.OrgId == Context.UserCurrentOrgId)
                {
                    selectIndex = i;
                }
                table.Rows.Add(row);
            }
            this.cbxCheckOrg.DataSource = table;
            cbxCheckOrg.DisplayMember = "Name";
            cbxCheckOrg.ValueMember = "OrgId";

            if (selectIndex > -1)
            {
                cbxCheckOrg.SelectedIndex = selectIndex;
                cbxCheckOrg_SelectedIndexChanged(null, null);
            }
                

        }

        private void Save_Click(object sender, EventArgs e)
        {
            if (bindDataSource.Rows.Count <= 0)
            {
                MessageBox.Show("保存失败,至少录入一条条码");
                return;
            }
            if (FPkValue == String.Empty)
            {
                MessageBox.Show("保存失败,备料单Id不可为空");
                return;
            }
            DataTable table = bindDataSource.Copy();
            string stockId = this.cbxOutStock.SelectedValue as string;
            if (stockId == null || stockId == "")
            {
                MessageBox.Show("保存失败,请设置仓库");
                return;
            }
            string orgId = this.cbxCheckOrg.SelectedValue as string;
            string stockNum=string.Empty;
            foreach (Stk stk in Context.Orgs[orgId]._stks)
            {
                if (stk.StkId == stockId)
                    stockNum = stk.Number;
            }

            DataSet DS = new DataSet();
            DS.Tables.Add(table);
            // k92815848ca6048b7a0e2a5b28c171573   销售订单到销售出库（中间单） 唯一标识
            string onlyMark = "k92815848ca6048b7a0e2a5b28c171573";
            string messStr = Context.Service.SaleOutStock(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, FPkValue, Context.Orgs[orgId].Number, stockNum, DS, onlyMark);

            if (messStr == null || messStr.Contains("保存成功"))
                ClearData();

            MessageBox.Show(messStr);
        }

        /// <summary>
        /// 清空所有数据
        /// </summary>
        private void ClearData()
        {
            FPkValue = string.Empty;
            this.tbxPreBillNo.Text = string.Empty;
            this.bindDataSource.Clear();
            this.DataGrid2Table.Clear();
        
        }
        /// <summary>
        /// 组织
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxCheckOrg_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearData();
            Type type = typeof(string);
            string org = cbxCheckOrg.SelectedValue as string;
            if (org != null && org != "")
            {
                List<Stk> listStk = Context.Orgs[org]._stks;
                DataTable table = new DataTable();
                table.Columns.Add("StkId", type);
                table.Columns.Add("Name", type);
                foreach (Stk s in listStk)
                {
                    DataRow dr = table.NewRow();
                    dr["StkId"] = s.StkId;
                    dr["Name"] = s.Name;
                    table.Rows.Add(dr);
                }
                cbxOutStock.DataSource = table;
                cbxOutStock.DisplayMember = "Name";
                cbxOutStock.ValueMember = "StkId";
            }
        }

        private void BillSubBody_DoubleClick(object sender, EventArgs e)
        {
            int index = this.BillSubBody.CurrentRowIndex;
            if (index != -1)
            {
                bindDataSource.Rows.RemoveAt(index);

            }
        }

        private void cbxOutStock_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearData();
        }

        private void tbxCode_TextChanged(object sender, EventArgs e)
        {

        }

        private void BillBody_CurrentCellChanged(object sender, EventArgs e)
        {

        }
    }
}